var mongoose = require('mongoose');
var Newsgl = require('../models/newsgl.model')// 引数据模型

// 新增
exports.create = function(req,res,next){
    var newsgl = new Newsgl(req.body); // 从req.body里获取参数对象，比如{name:'vane',gender:'男',city:'杭州'....}

    newsgl.save()
    .then(data=>{
        res.json(data)
    })
    
}

//修改
exports.update = function(req,res,next){
  
    var id = req.params.id; // req.param('id')
    // 现在操作的都是mongoose而不是mongodb
    Newsgl.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
    .then(data=>{
        res.json(data); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
    })
}

//删除
exports.remove = function(req,res,next){
    var id = req.params.id;
    Newsgl.findByIdAndRemove(id,function(err,doc){
        res.json({msg:'数据删除成功',status:200})
    })
} 


exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var rows = (req.body.rows) ? req.body.rows : 2;

    var queryCondition = {};
    var title;
    if( req.body.title && req.body.title.trim().length>0 ){
        title = req.body.title;
        queryCondition = {"title":new RegExp(title,'i')}
    }
    if( req.body.cateId && req.body.cateId.trim().length>0 ){
        cateId = req.body.cateId;
        queryCondition = {"cateId":cateId}
    }
    if( req.body.author && req.body.author.trim().length>0 ){
        author = req.body.author;
        queryCondition = {"author":author}
    }
    if( req.body.btitle && req.body.btitle.trim().length>0 ){
        btitle = req.body.btitle;
        queryCondition = {"btitle":btitle}
    }
    if( req.body.content && req.body.content.trim().length>0 ){
        content = req.body.content;
        queryCondition = {"content":content}
    }
    if( req.body.date && req.body.date.trim().length>0 ){
        date = req.body.date;
        queryCondition = {"date":date}
    }
    
    

    Newsgl.paginate(queryCondition, { page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;

       res.json(result)
    });
}